package com.owen.util;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;

public class GetMapUtil {


    public Map<String, String> getMap() {
        ApplicationUtil applicationUtil = new ApplicationUtil();
        Properties application = applicationUtil.getApplication();
        String txtToMaoEncoding = Optional.ofNullable(application.getProperty("pdfTxtToMaoEncoding")).orElseGet(() ->
            "UTF-8"
        );
        String mapTxtPath = Optional.ofNullable(application.getProperty("pdfMapTxtPath")).orElseGet(() ->
                "/map.txt"
        );
        String path = application.getProperty("path");

        InputStream fis = getClass().getResourceAsStream(mapTxtPath);
        Map<String, String> map = new HashMap<String, String>();
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(fis, txtToMaoEncoding);
            br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null) {
                // 如果 t x t文件里的路径 不包含---字符串       这里是对里面的内容进行一个筛选
                if (line.lastIndexOf("---") < 0) {
                    String[] split = line.split(" : ");
                    if (Optional.ofNullable(path).isPresent()){
                        map.put(new StringBuilder(split[0].trim()).replace(0,1,path).toString(), split[1].trim());
                    }else {
                        map.put(split[0].trim(), split[1].trim());
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
                if (isr != null)
                    isr.close();
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return map;
    }
}
